package com.hhq.usercenter.security;

import cn.hutool.core.collection.CollUtil;
import com.hhq.usercenter.domain.pojo.MenuInfo;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * <p>Description: 动态权限决策管理 </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/1/9 18:35
 */
@Component
public class DynamicAccessDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        // 当接口未被配置资源时直接放行
        if (CollUtil.isEmpty(configAttributes)) {
            return;
        }
        //创建一个资源迭代器
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();
        while (iterator.hasNext()) {
            ConfigAttribute configAttribute = iterator.next();
            //将访问所需资源或用户拥有资源进行比对
            String needAuthority = configAttribute.getAttribute();
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                MenuGrantedAuthority menuGrantedAuthority = (MenuGrantedAuthority) grantedAuthority;
                List<MenuInfo> menus = menuGrantedAuthority.getMenus();
                for (MenuInfo menuInfo : menus) {
                    if (needAuthority.trim().equals(menuInfo.getId() + ":" + menuInfo.getName())) {
                        return;
                    }
                }
            }
        }
        throw new AccessDeniedException("抱歉，您没有访问权限");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
